package com.mimosa.common.view;

import java.util.Date;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mimosa.common.entity.BaseEntity;
import com.mimosa.util.config.Page;

public class EasyUiDataGrid<T extends BaseEntity> {
	/**
	 * 日志记录器
	 */
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 分页对象
	 */
	private Page<T> page;
	/***
	 * 字符串结果对象
	 */
	private StringBuilder builder = new StringBuilder();

	public EasyUiDataGrid(Page<T> page) {
		this.page = page;
	}

	protected String[] getColumnNames(T entity) {
		return DataViewHelper.INS.getEntityNames(entity.getClass().getSimpleName());
	}

	void generateDataGrid() {
		this.builder.append("{\"total\":\"");
		this.builder.append(this.page.getTotalCount());
		this.builder.append("\",\"rows\":[");
		Object valueObj = null;
		Object valueStr = null;
		for (T t : this.page.getResult()) {
			this.builder.append("{");
			for (String name : getColumnNames(t)) {
				this.builder.append("\"").append(name.replace('.', '_')).append("\":\"");
				try {
					valueObj = PropertyUtils.getNestedProperty(t, name);
				} catch (Exception e) {
					logger.error("can not get entity property value by name : {}", name, e);
				}
				if (valueObj instanceof Date) {
					valueStr = DateFormatUtils.ISO_DATE_FORMAT.format(valueObj);
				} else {
					valueStr = ObjectUtils.toString(valueObj);
				}
				this.builder.append(valueStr).append("\",");
			}
			this.builder.deleteCharAt(this.builder.length() - 1);
			this.builder.append("},");
		}

		if (this.page.getTotalCount() > 0) {
			this.builder.deleteCharAt(this.builder.length() - 1);
		}
		this.builder.append("]}");
	}

	public String toString() {
		if (this.builder.length() < 1) {
			generateDataGrid();
		}
		return this.builder.toString();
	}
}